import { chunkArray } from "../utils";

// 列表名接口
function getPageDataUrl() {
  return `${location.origin}/dpas-api-prefix/dpas/discuss/bargain_page`;
}
// 同意建议价接口
function getDoAgreeToNegotiateUrl() {
  return `${location.origin}/dpas-api-prefix/dpas/discuss/batch_handle_cost_discuss`;
}

// 获取当前页数
function getCurrentPage() {
  return Number(
    document.querySelector(".so-pagination-current")?.textContent || 1
  );
}

// 获取PageSize
function getPageSize() {
  const pageSizeText =
    document.querySelector(".so-select-result")?.textContent || "";
  return Number(pageSizeText.match(/^\d+/)?.[0] || 10);
}

// 获取总页数
function getTotalPageSize() {
  const endPageElement = document
    .querySelector(".so-pagination-links")
    ?.querySelector(".so-pagination-item:nth-last-child(2)");

  return Number(endPageElement?.textContent || 0);
}

// 格式化列表数据
function formatListDataToMap({
  data,
  skuCodeList,
  productBySkuAndCostPriceMap,
  productBySkuCurrencyMap,
}: {
  data: any[];
  skuCodeList: any[];
  productBySkuAndCostPriceMap: any;
  productBySkuCurrencyMap: any;
}) {
  return data.reduce((obj, dataItem: any) => {
    const { bargain_sn, sku_cost_prices, document_sn } = dataItem;
    if (bargain_sn && document_sn) {
      obj[bargain_sn] = {
        bargain_sn,
        document_sn,
        skuPriceMap: {},
      };
      const skuCostPrices = sku_cost_prices || [];
      skuCostPrices.forEach((skuItem: any) => {
        const { sku_code, suggest_cost_price, cost_price_histories } = skuItem;
        obj[bargain_sn].skuPriceMap[sku_code] = suggest_cost_price;
        skuCodeList.push(sku_code);
        productBySkuAndCostPriceMap[sku_code] =
          cost_price_histories?.[0]?.cost_price;
        productBySkuCurrencyMap[sku_code] =
          cost_price_histories?.[0]?.currency;
      });
    }

    return obj;
  }, {});
}

// 获取商品列表中的信息
async function getProductBySkuMap({
  pageNum = 1,
  pageSize = 10,
  skuCodeList = [],
  productBySkuAndCostPriceMap = {},
  productBySkuCurrencyMap = {},
}: {
  pageNum: number;
  pageSize: number;
  skuCodeList: any[];
  productBySkuAndCostPriceMap: any;
  productBySkuCurrencyMap: any;
}) {
  const pageDataUrl = getPageDataUrl();
  const response = await fetch(
    `${pageDataUrl}?page_num=${pageNum}&page_size=${pageSize}`,
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ bargain_status: 1 }),
    }
  ).then((res) => res.json());
  const data = response?.info?.data || [];
  return formatListDataToMap({
    data,
    skuCodeList,
    productBySkuAndCostPriceMap,
    productBySkuCurrencyMap,
  });
}

// 操作时格式化数据
function formatSaveParams({
  productBySkuMap,
  skuPurchasePriceMap,
  multiplier,
}: {
  productBySkuMap: any;
  skuPurchasePriceMap: any;
  multiplier: number;
}) {
  const confirm_infos: any[] = [];
  let successTotal = 0;
  let failTotal = 0;
  let skipCount = 0;
  for (const key of Object.keys(productBySkuMap)) {
    const { bargain_sn, document_sn, skuPriceMap } = productBySkuMap[key];
    let isAllSkuMatch = true;
    let isSkip = false;
    for (const skuCode of Object.keys(skuPriceMap)) {
      const hasErpData = skuCode in skuPurchasePriceMap;
      if (!hasErpData) {
        isSkip = true;
        break;
      }
      const skuPriceNumber = Number(skuPriceMap[skuCode]);
      const contrastNumber =
        Number(skuPurchasePriceMap[skuCode]) * Number(multiplier);
      const inMathRule = skuPriceNumber > contrastNumber;
      if (!inMathRule) {
        isAllSkuMatch = false;
      }
    }
    if (isSkip) {
      skipCount++;
    } else {
      let discuss_audit_type = isAllSkuMatch ? 1 : 2;
      if (isAllSkuMatch) {
        successTotal++;
      } else {
        failTotal++;
      }
      confirm_infos.push({
        discuss_sn: bargain_sn,
        document_sn,
        discuss_audit_type,
      });
    }
  }

  if (!confirm_infos.length) {
    return { paramsList: [], successTotal, failTotal, skipCount };
  }
  const paramsList = chunkArray(confirm_infos, 500).map((item) => {
    return {
      confirm_infos: item,
    };
  });
  return { paramsList, successTotal, failTotal, skipCount };
}

export default {
  getCurrentPage,
  getPageSize,
  getTotalPageSize,
  getProductBySkuMap,
  formatSaveParams,
  getDoAgreeToNegotiateUrl,
};
